package com.ming.liteflow.controller;

import com.ming.common.beetl.util.Result;
import com.ming.common.beetl.util.StrUtil;
import com.ming.common.xxljob.annotation.PermissionLimit;
import com.ming.common.liteflow.core.task.IvyTask;
import com.ming.common.liteflow.vo.IvyTaskVo;
import com.ming.common.Options;
import com.ming.common.SortBy;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.page.PageResult;
import org.beetl.sql.core.query.LambdaQuery;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/liteflow/task")
public class LiteFlowTaskController {

    @Resource
    private SQLManager sqlManager;

    @PostMapping("/page")
    @PermissionLimit(limit = false)
    public Result<PageResult<IvyTask>> page(@RequestBody IvyTaskVo vo){
        LambdaQuery<IvyTask> lambdaQuery = sqlManager.lambdaQuery(IvyTask.class);
        lambdaQuery.andLike(IvyTask::getTaskId, LambdaQuery.filterLikeEmpty(vo.getTaskId()));
        lambdaQuery.andLike(IvyTask::getTaskName, LambdaQuery.filterLikeEmpty(vo.getTaskName()));
        Options options = vo.getOptions();
        List<SortBy> sortBy = options.getSortBy();
        for (SortBy sort : sortBy) {
            if ("desc".equalsIgnoreCase(sort.getOrder())) {
                lambdaQuery.desc(StrUtil.camelToSnake(sort.getKey()));
            } else {
                lambdaQuery.asc(StrUtil.camelToSnake(sort.getKey()));
            }
        }
        PageResult<IvyTask> page = lambdaQuery.page(options.getPage(), options.getItemsPerPage());
        return Result.OK(page);
    }

    @PostMapping("/add")
    @PermissionLimit(limit = false)
    public Result<?> add(@RequestBody IvyTask item){
        LambdaQuery<IvyTask> query = sqlManager.lambdaQuery(IvyTask.class);
        int i = query.insert(item);
        return Result.OK(i);
    }

    @PostMapping("/update")
    @PermissionLimit(limit = false)
    public Result<Object> update(@RequestBody IvyTask item){
        LambdaQuery<IvyTask> lambdaQuery = sqlManager.lambdaQuery(IvyTask.class);
        lambdaQuery.andNotEq(IvyTask::getId, item.getId());
        lambdaQuery.andEq(IvyTask::getTaskId, item.getTaskId());
        long count = lambdaQuery.count();
        if(count > 0){
            return Result.error("任务ID重复");
        }
        int i = sqlManager.updateById(item);
        return Result.OK("更新成功", i);
    }

    @PostMapping("/delete")
    @PermissionLimit(limit = false)
    public Result<Integer> delete(@RequestBody IvyTask item){
        LambdaQuery<IvyTask> lambdaQuery = sqlManager.lambdaQuery(IvyTask.class);
        lambdaQuery.andEq(IvyTask::getId, item.getId());
        int i = lambdaQuery.delete();
        return Result.OK("删除成功",i);
    }
}
